// 统一日志系统
import winston from 'winston';
import config from '../config/config.js';

const { createLogger, format, transports } = winston;
const { combine, timestamp, printf, colorize, errors } = format;

// 自定义日志格式
const logFormat = printf(({ level, message, timestamp, stack, ...meta }) => {
  let log = `${timestamp} [${level.toUpperCase()}]: ${message}`;
  
  if (stack) {
    log += `\n${stack}`;
  }
  
  if (Object.keys(meta).length > 0) {
    log += `\n${JSON.stringify(meta, null, 2)}`;
  }
  
  return log;
});

// 创建日志记录器
const logger = createLogger({
  level: config.app.logLevel,
  format: combine(
    errors({ stack: true }),
    timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
    logFormat
  ),
  defaultMeta: { service: config.app.name },
  transports: [
    // 控制台输出（开发环境）
    new transports.Console({
      format: combine(
        colorize(),
        logFormat
      )
    }),
    
    // 文件输出（生产环境）
    new transports.File({ 
      filename: 'logs/error.log', 
      level: 'error',
      maxsize: 5242880, // 5MB
      maxFiles: 5
    }),
    new transports.File({ 
      filename: 'logs/combined.log',
      maxsize: 5242880, // 5MB
      maxFiles: 5
    })
  ],
  
  // 异常处理
  exceptionHandlers: [
    new transports.File({ filename: 'logs/exceptions.log' })
  ],
  
  // 拒绝处理
  rejectionHandlers: [
    new transports.File({ filename: 'logs/rejections.log' })
  ]
});

// 请求日志中间件
const requestLogger = (req, res, next) => {
  const start = Date.now();
  
  res.on('finish', () => {
    const duration = Date.now() - start;
    logger.info(`${req.method} ${req.originalUrl}`, {
      status: res.statusCode,
      duration: `${duration}ms`,
      ip: req.ip,
      userAgent: req.get('User-Agent')
    });
  });
  
  next();
};

// 错误日志中间件
const errorLogger = (error, req, res, next) => {
  logger.error('服务器错误', {
    error: error.message,
    stack: error.stack,
    url: req.originalUrl,
    method: req.method,
    ip: req.ip
  });
  
  next(error);
};

// 性能监控
const performanceLogger = {
  start: (operation) => {
    const startTime = Date.now();
    return {
      end: () => {
        const duration = Date.now() - startTime;
        logger.debug(`性能监控: ${operation}`, { duration: `${duration}ms` });
        return duration;
      }
    };
  }
};

export {
  logger,
  requestLogger,
  errorLogger,
  performanceLogger
};